/**   
* @Title: ImgJsonDecoderImpl.java 
* @Package net.gdface.service.search 
* @Description: TODO 
* @author guyadong   
* @date 2015年5月13日 下午8:20:28 
* @version V1.0   
*/
package net.gdface.service.search;

import java.net.MalformedURLException;
import java.net.URI;

import static net.gdface.utils.MiscellaneousUtils.createURI;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * @author guyadong
 *
 */
public abstract class ImgJsonDecoderImpl implements ImgJsonDecoder {

	/**
	 * 
	 */
	public ImgJsonDecoderImpl() {
	}
	
	public abstract String getRef(JSONObject jo) throws JSONException;
	public abstract String getUrl(JSONObject jo) throws JSONException;	
	public abstract int getWidth(JSONObject jo) throws JSONException;
	public abstract int getHeight(JSONObject jo) throws JSONException;
	
	@Override
	public ImgInfo create(JSONObject jo) throws MalformedURLException, JSONException{
		return new ImgInfo(this.getImgLocation(jo), this.getImgRef(jo), getWidth(jo), getHeight(jo), getInterval(jo), this.getMd5Ref(jo), this.isRetry(jo), this.getKeyword(jo));
	}

	public URI getImgLocation(JSONObject jo) throws MalformedURLException, JSONException{
		return createURI(getUrl(jo));
	}

	public URI getImgRef(JSONObject jo) throws MalformedURLException, JSONException{
		return createURI(getRef(jo));
	}

	public int getInterval(JSONObject jo) {
		//host访问间隔,如果json对象中有指定就使用指定的值，否则为-1（系统默认值）
		try {
			return jo.getInt(KEY_INTERVAL);
		} catch (JSONException e) {
			return -1;
		}
	}

	public String getKeyword(JSONObject jo) {		
		try {
			return jo.getString(KEY_KEYWORD);
		} catch (JSONException e) {
			return null;
		}
	}
	
	public String getMd5Ref(JSONObject jo) {
		try {
			return jo.getString(KEY_MD5REF);
		} catch (JSONException e) {
			return null;
		}
	}	
	public boolean isRetry(JSONObject jo) {
		//是否重试标记,如果json对象中有指定就使用指定的值，否则为false
		try {
			return jo.getBoolean(KEY_RETRY);
		} catch (JSONException e) {
			return false;
		}
	}
}
